
/*
 *
 * All Rights Reserved.
 */
package com.model.demo.designmodel.proxy.dynamicproxy.dbroute;

import com.model.demo.designmodel.proxy.dbroute.DynamicDataSourceEntity;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * OrderServiceDynamicProxy
 *
 * @author Liao Dongshan, 2019年06月06日
 *
 */
public class OrderServiceDynamicProxy implements InvocationHandler {

    private SimpleDateFormat sdf=new SimpleDateFormat("yyyy");

    private Object proxyObj;

    public Object getInstance(Object proxyObj){
        this.proxyObj=proxyObj;
        Class<?> clazz = proxyObj.getClass();
        return Proxy.newProxyInstance(clazz.getClassLoader(),clazz.getInterfaces(),this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        before(args[0]);
        Object invoke = method.invoke(this.proxyObj, args);
        after();
        return invoke;
    }

    private void after() {
        DynamicDataSourceEntity.restore();
    }

    private void before(Object target) {
        try {
            Method getCreateTime = target.getClass().getMethod("getCreateTime", null);
            Date createTime = (Date)getCreateTime.invoke(target, null);
//            Date createTime = order.getCreateTime();
            Integer year = Integer.parseInt(sdf.format(createTime));
            System.out.println("【DB_" + year + "】数据源处理");
            DynamicDataSourceEntity.set(year);
        }catch (Exception e){
            e.printStackTrace();
        }
    }


}
